package com.mcf.xiaolinju.token;

import com.mcf.xiaolinju.interceptor.UserLoginException;
import com.mcf.xiaolinju.interceptor.UserLoginInvalidException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;

public class JwtUtil {
    final static String base64EncodedSecretKey="123456";//私钥
    final  static long TOKEN_EXP =1000*60*60*10;
    public static String getTokn (int id,String name){
        return Jwts.builder()
                .setId(String.valueOf(id))
                .setSubject(name)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis()+ TOKEN_EXP))
                .signWith(SignatureAlgorithm.HS256,base64EncodedSecretKey)
                .compact();
    }
    /*** 检查token,只要不正确就会抛出异常**/
    public static Claims checkToken(String token) throws Exception {
        try {
            final Claims claims = Jwts.parser().setSigningKey(base64EncodedSecretKey).parseClaimsJws(token).getBody();
            return claims;
        } catch (ExpiredJwtException e1) {
            throw new UserLoginInvalidException("登录信息过期，请重新登录");
        } catch (Exception e) {
            throw new UserLoginException("用户未登录，请重新登录");
        }
    }
}
